// utils/ResourceUtil.ets
import common from '@ohos.app.ability.common';
import { buffer } from '@kit.ArkTS';
import { BufferUtil } from './BufferUtil';

export class ResourceUtil {
  private static instance: ResourceUtil;
  private context: common.Context;

  private constructor(context: common.Context) {
    this.context = context;
  }

  public static getInstance(context: common.Context): ResourceUtil {
    if (!ResourceUtil.instance) {
      ResourceUtil.instance = new ResourceUtil(context);
    }
    return ResourceUtil.instance;
  }

  /**
   * 读取raw目录下的文本文件
   * @param fileName 文件名
   * @returns
   */
  async readRawFile(fileName: string): Promise<string> {
    try {
      // 获取资源管理器
      let resourceMgr = await this.context.resourceManager;

      // 读取raw目录下的文件
      let rawFile = await resourceMgr.getRawFileContent(`${fileName}`);

      // 转换为Buffer
      let buf = buffer.from(rawFile);

      // 转换为字符串
      let content = buf.toString('utf8');

      return JSON.stringify(content);
    } catch (error) {
      console.error(`Failed to read raw file: ${fileName}`, error);
      throw error;
    }
  }

  /**
   * 读取raw目录下的二进制文件
   * @param fileName
   * @returns
   */
  async readRawFileBuffer(fileName: string): Promise<ArrayBuffer> {
    try {
      let resourceMgr = await this.context.resourceManager;
      let uint8 = await resourceMgr.getRawFileContent(`${fileName}`);
      let arrbuff = await BufferUtil.uint8ArrayToArrayBuffer(uint8);
      return arrbuff;
    } catch (error) {
      console.error(`Failed to read raw file buffer: ${fileName}`, error);
      throw error;
    }
  }

  /**
   * 读取json文件
   * @param fileName
   * @returns
   */
  async readJsonFile(fileName: string): Promise<any> {
    try {
      const content = await this.readRawFile(fileName);
      return JSON.parse(content);
    } catch (error) {
      console.error(`Failed to read json file: ${fileName}`, error);
      throw error;
    }
  }


}